package com.caiden_micheal.base.utils;

import com.caiden_micheal.base.constant.LoggerHead;
import com.caiden_micheal.base.properties.JWTProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
public class JwtUtil {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    public static JWTProperties jwtProperties;

    @Resource
    public void setJwtProperties(JWTProperties jwtProperties) {
        JwtUtil.jwtProperties = jwtProperties;
    }

    public static String createToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).setExpiration(new Date(System.currentTimeMillis() + jwtProperties.getExpirationTime() * 1000)).signWith(SignatureAlgorithm.HS256, jwtProperties.getSecretKey()).compact();
    }

    public static Claims validateUserToken(String token) {
        try {
            return Jwts.parser().setSigningKey(JwtUtil.jwtProperties.getSecretKey()).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            logger.error(LoggerHead.errorHead() + "JWT parsing error! Receive Token: " + token);
        }
        return null;
    }
}
